package com.ruoyi.project.tool.swagger.UserController;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.icbc.api.IcbcApiException;
import com.icbc.api.utils.IcbcEncrypt;
import com.icbc.api.utils.IcbcSignature;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.sign.AesUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Ide;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.annotation.SignatureValidation;
import com.ruoyi.framework.aspectj.lang.enums.OperatorType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysBank;
import com.ruoyi.project.system.domain.SysCompany;
import com.ruoyi.project.system.domain.SysMobileUser;
import com.ruoyi.project.system.domain.SysReceive;
import com.ruoyi.project.system.domain.vo.UserInfo;
import com.ruoyi.project.system.domain.vo.WxLoginInfo;
import com.ruoyi.project.system.service.ISysBankService;
import com.ruoyi.project.system.service.ISysCompanyService;
import com.ruoyi.project.system.service.ISysMobileUserService;
import com.ruoyi.project.system.service.ISysReceiveService;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import okhttp3.HttpUrl;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import test.util.SequenceUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("/mobileUser")
public class MobileUserController extends BaseController {

    private static String AESKey = "ev955rIWVhV4WBcsvV9B0w==";
//    private static String AESKey = "0Hr2Hd5RPp0bBnKx+LNqqw==";
    private static String encrypt_type = "AES";
    private static String sign_type = "RSA2";
    private static String charset = "UTF-8";

    private static String mer_private_key="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCvue6taEhlsPXGfQ0+LnnpyAYw8AD2ePPKNTYzmB/UuOQf5iEW2/g2bCnvMJzjSKMvwGH/11ntT9Xy8PALLPN/VMUtNNLT7LCNIJVHvir3l1Z0uNxXgmMqonbLPjcTl5E+VgwXPaGGMUNyPAvqAe1XeD64IHfYOLA2dkH0/YIcc1F+ToqgizR91DsByDMNXg+xrbO4qbV9C3fbrxlIvFl/3eOcRwPG1E2wO9FleeDd4c3YymVLmRHEd3902tdPMpYjo/iHHlPTF2WbIuHo82YwDZbOmDGltoVpFM92W8U1wqGRAZf75/ptDQCylYzqIz8IGP57BAlIkAcQ4uRad8MnAgMBAAECggEBAK3r+K7oZ78+RgMOAe1pUoBv2LDW2h0X2TJpOBwYlGiWFjL8MgPN8vzqURbLpnvNiLXaUyREoFygh8DLdsmY0+dSn1T+0yutN5B2j0lSjnQ+9PLRhEOYaU3pPmoqSZi6iqaHw6+88AFBAOAvThttjNrlyC209OisMru0j9NKlVxRn+RXVLO6CwApi7E5tGBX91gjhS5EvpoMDrBpKaV5dau6ijkFsBi+4li41kWEJ93Cd3josm6U6zyTAasjW1q/xgPlR/c4UbQqQWsNZMgeGG+L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oyI04svWPluXMfVXoTJliQza26HqKZw6nrlnGpIvtJnYCRr1v2YNzS5kqjEvggUPVRM8u3OenODQxtfxMABwKBgEz7DLF0LsezuEbGNblu75PYUdFJfXF7Yu5KuvF1Gs36SBiJAJ/tDVtIp4O61ujaikPQpdDMHc2M/fmPDC0hyOsB4mWw5+7jSsX+mi5TebqySgnZ+8m2d4Omrz5N27V2J5pefmN9kQWwJJolnKt7X2lUBgIWSdA3miWu7n8S/0y5AoGBALyKWZC6ICCzBv09xf02HDMy0aLPmg9400KbqvUA0apQExSoCqtKERf84x0fR0ToyyqdcisNwXTILFr1qnEMIFck1Tr2GH9Z2XnBco3myEZjn3HFFl0aU2kkL0KfaOznflaloJWUndvm2MAcwCkqRSYreDwVd2Z9hN/96/y11leN";


    @Autowired
    private WxMaService wxService;

    @Autowired
    private ISysReceiveService sysReceiveService;

    @Autowired
    private ISysCompanyService sysCompanyService;

    @Autowired
    private ISysMobileUserService sysMobileUserService;

    @Autowired
    private RedisTemplate redisTemplate;
    public static void main(String[] args) throws IcbcApiException {
        String content = IcbcEncrypt.decryptContent("FLtBwl/txLKtu+xNbBKc0e00TKhOqR63db6Ip5nrdeHbVt5nbYyMKXCGVwpgQIWrIW+5f5fS9AjNNZSEuwkci03YsMeNw9MyNravxXZ6p3KcphLbPDpga16HesIPmzkPAwoa40SOGXXbmi3MZiCPBESNhTN8Y1Vh+dRTTavlXAP122eMnd+/bWN/dL+Pjt01Y9ELDO3qAuthVW0pgq6sKdw01EaZ0eJsVm3yJI/LOJ6VZGih0H4IuGVoV9ZvCDDFjWmuEr292VgnkFqstbKh0RgeuyTgigZCfc7PlOPvdBpViddILHMrvITVPP7h08qrgzjiNKhdclFkMTDoeTlalmjEkb3CmfWBKU5aSvoBt1k=", encrypt_type, AESKey, charset);
        System.out.println(content);
    }

    //    biz_content=加密后的参数内容&timestamp=201407230000714
    @PostMapping("/qrqmActivity")
    public JSONObject luck(HttpServletRequest request ) throws WxErrorException, IcbcApiException {
        String biz_content = request.getParameter("biz_content");
        System.out.println(biz_content);
        String content = IcbcEncrypt.decryptContent(biz_content, encrypt_type, AESKey, charset);
        JSONObject object = JSONObject.parseObject(content);
        //活动编码
        String rule = object.getString("activity_id");
        //用户id
        String bankUserId = object.getString("cust_id");
        //银行流水号
        String secret = object.getString("serial_no");

        String prizeNo = object.getString("prize_no");

        SysReceive query = new SysReceive();
        query.setBankUserId(bankUserId);
        query.setPhone(prizeNo);
        query.setOutlets(rule);
        List<SysReceive> lists = sysReceiveService.selectSysReceiveList(query);
        if (!lists.isEmpty()) {
            SysReceive sysReceive = lists.get(0);
            if ("0".equals(sysReceive.getStatus())) {
                return success(sysReceive);
            } else {
                return error();
            }
        } else {
            query.setTypeName(content);
            query.setStatus("0");
            query.setSecret(secret);
            query.setCreateTime(new Date());
            sysReceiveService.insertSysReceive(query);
            return success(query);
        }
    }

    public JSONObject error() throws WxErrorException {
        JSONObject obj=new JSONObject();
        Map resultMap = new HashMap();
        resultMap.put("return_code", 1);
        resultMap.put("return_msg", "用户已领取过");
        resultMap.put("wx_award", "");
        obj.put("data",resultMap);
        obj.put("status",1);
        obj.put("message","失败");
        return obj;
    }

    public JSONObject success(SysReceive sysReceive) throws WxErrorException {
        JSONObject obj=new JSONObject();
        String url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=".concat(wxService.getAccessToken(true));
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("path", "/pages/index/index");
        jsonObject1.put("query", "outlets=".concat(sysReceive.getOutlets()) + "&bankUserId=".concat(sysReceive.getBankUserId()) + "&secret=".concat(sysReceive.getSecret()));
        jsonObject.put("jump_wxa", jsonObject1);
        byte[] post = HttpClientUtils.post(url, jsonObject.toJSONString());
        String res = new String(post);
        System.out.println("活动链接:" + res);
        String link = JSONObject.parseObject(res).getString("openlink");
        Map resultMap = new HashMap();
        resultMap.put("return_code", 0);
        resultMap.put("return_msg", "受理成功");
        resultMap.put("wx_award", link);
//        resultMap.put("wx_award", "http://gsqy.jszechao.com/webPage?wx="+URLEncoder.encode(link));
        obj.put("data",resultMap);
        obj.put("status",0);
        obj.put("message","成功");
        return obj;
    }

    @PostMapping("/authorizedLogin")
    public AjaxResult authorizedLogin(@RequestBody SysReceive receive) throws Exception {
        String openId = gettoken(receive.getCode());
        SysMobileUser query = new SysMobileUser();
        query.setOpenId(openId);
        List<SysMobileUser> lists = sysMobileUserService.selectSysMobileUserList(query);
        if(lists.isEmpty()){
            SysMobileUser sysMobileUser=new SysMobileUser();
            sysMobileUser.setOpenId(openId);
            sysMobileUser.setCreateTime(new Date());
            sysMobileUserService.insertSysMobileUser(sysMobileUser);
        }
        return AjaxResult.success("操作成功",openId);
    }

    @PostMapping("/getLuck")
    public AjaxResult getLuck(@RequestBody SysReceive receive) throws Exception {
        System.out.println("参数:"+JSONObject.toJSONString(receive));
        String openId = receive.getOpenId();
        receive.setOpenId(null);
        receive.setStatus("0");
        List<SysReceive> lists = sysReceiveService.selectSysReceiveList(receive);
        receive.setOpenId(openId);
        if (lists.isEmpty()) {
            return AjaxResult.error("没有领取资格~");
        } else {
            SysReceive sysReceive = lists.get(0);
            sysReceive.setOpenId(openId);
            //获取可以发放的立减金
            SysCompany sysCompanyQuery = new SysCompany();
            sysCompanyQuery.setRule(sysReceive.getOutlets());
            List<SysCompany> stocks = sysCompanyService.selectSysCompanyLists(sysCompanyQuery);
            if (stocks.isEmpty()) {
                return AjaxResult.error("不存在待领取的立减金~");
            }
            String remark = "";
            String type = "";
            String name="";
            for (int i = 0; i < stocks.size(); i++) {
                SysCompany company = stocks.get(i);
                String date = SequenceUtils.getCurentDate();
                String key = "serial.gooods:" + date;
                //** 自增 *//*
                long sequence = redisTemplate.opsForValue().increment(key);
                String orderNo = date + SequenceUtils.getSequence(sequence);
                String url = "https://api.mch.weixin.qq.com/v3/marketing/favor/users/" + openId + "/coupons";
                JSONObject datas = new JSONObject();
                datas.put("out_request_no", orderNo);//订单号
                datas.put("stock_id", stocks.get(i).getScore());//代金券批次id也就是商品编号
                datas.put("appid", wxService.getWxMaConfig().getAppid());
                datas.put("stock_creator_mchid", "1605617216");//商户号
                SignUtil signUtil = new SignUtil();
                JSONObject results = null;
                try {
                    results = HttpUtil.doPost(url, datas, signUtil.getToken("POST", HttpUrl.parse(url), datas.toJSONString()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (results.containsKey("coupon_id")) {
                    if (i == 0) {
                        type += stocks.get(i).getScore();
                        remark += results.getString("coupon_id");
                        name += stocks.get(i).getName();
                    } else {
                        type = type + "," + stocks.get(i).getScore();
                        remark = remark + "," + results.getString("coupon_id");
                        name = name + "," + stocks.get(i).getName();
                    }
                }
            }
            String apis="https://ext.js.icbc.com.cn/rexqrqm/api/qrqmMobile/custPrize/notifyActivityResult?";
            if (type.equals("")) {
                JSONObject data=new JSONObject();
                data.put("serial_no",sysReceive.getSecret());
                data.put("activity_id",sysReceive.getOutlets());
                data.put("cust_id",sysReceive.getBankUserId());
                data.put("open_id",sysReceive.getOpenId());
                data.put("trade_stat","1");
                data.put("trade_msg","赠送失败");
                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
                SimpleDateFormat sdf1=new SimpleDateFormat("HHmmss");
                data.put("trade_date",sdf.format(new Date()));
                data.put("trade_time",sdf1.format(new Date()));
                String biz_content = data.toJSONString();
                biz_content = IcbcEncrypt.encryptContent(biz_content, encrypt_type, AESKey, charset);
                long timestamp = new Date().getTime();
                //数据RSA签名
                String sign="";
                sign = "app_id=1000000001&biz_content="+biz_content+"&timestamp="+timestamp+"&version=1.0";
                String signs = IcbcSignature.sign(sign, sign_type, mer_private_key, charset);
                sign=apis+sign+"&sign="+signs;
                JSONObject results = null;
                try {
                    results = HttpUtil.doPosts(sign);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return AjaxResult.error("领取失败，请联系客服~");
            } else {
                sysReceive.setRemark(remark);
                sysReceive.setType(type);
                sysReceive.setStatus("1");
                sysReceive.setUpdateTime(new Date());
                JSONObject data=new JSONObject();
                data.put("serial_no",sysReceive.getSecret());
                data.put("activity_id",sysReceive.getOutlets());
                data.put("cust_id",sysReceive.getBankUserId());
                data.put("open_id",sysReceive.getOpenId());
                data.put("trade_stat","0");
                data.put("trade_msg","赠送成功");
                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
                SimpleDateFormat sdf1=new SimpleDateFormat("HHmmss");
                data.put("trade_date",sdf.format(new Date()));
                data.put("trade_time",sdf1.format(new Date()));
                String biz_content = data.toJSONString();
                biz_content = IcbcEncrypt.encryptContent(biz_content, encrypt_type, AESKey, charset);
                long timestamp = new Date().getTime();
                //数据RSA签名
                String sign="";
                sign = "app_id=1000000001&biz_content="+biz_content+"&timestamp="+timestamp+"&version=1.0";
                String signs = IcbcSignature.sign(sign, sign_type, mer_private_key, charset);
                sign=apis+sign+"&sign="+signs;
                JSONObject results = null;
                try {
                    results = HttpUtil.doPosts(sign);
                    System.out.println("回调结果:"+results.toJSONString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                int flag=sysReceiveService.updateSysReceive(sysReceive);
                if(flag>0){
                    return AjaxResult.success("操作成功",name);
                }
                return AjaxResult.error();
            }
        }
    }
    public String gettoken(String code) throws UnsupportedEncodingException {
        String openid = "";
        String strAppId = wxService.getWxMaConfig().getAppid();//就是appid
        String strSecret = wxService.getWxMaConfig().getSecret();//就是secret
        String strUrl = " https://api.weixin.qq.com/sns/oauth2/access_token";
        strUrl += "?appid=" + strAppId;
        strUrl += "&secret=" + strSecret;
        strUrl += "&code=" + code; //微信反馈的code
        strUrl += "&grant_type=authorization_code";
        byte[] res = null;
        org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet();
        try {
            URL url = new URL(strUrl);
            URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
            httpget = new HttpGet(uri);
            HttpResponse response = null;
            response = httpclient.execute(httpget);
            res = IOUtils.toByteArray(response.getEntity().getContent());
        } catch (Exception e) {
            throw new BaseException("微信获取错误!");

        } finally {
            if (httpget != null) {
                httpget.abort();
            }
            httpclient.getConnectionManager().shutdown();
        }
        JSONObject jsonObject = JSONObject.parseObject(new String(res, "utf-8"));
        System.out.println(jsonObject.toJSONString());
        if (!jsonObject.containsKey("openid")) {
            throw new BaseException("微信授权报错");
        }
        openid = jsonObject.getString("openid");
        return openid;
    }




}
